package com.itheima.service.impl;

import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import com.itheima.service.EmpService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmployeeMapper EmployeeMapper;

    @Override
    public Employee login(Employee employee) {
        //③. 如果没有查询到, 则返回登录失败结果

        Employee empLogin = EmployeeMapper.selectByUserName(employee.getUsername());
        if(empLogin == null){
           throw new RuntimeException("该用户不存在");
        }
        //④. 密码比对，如果不一致, 则返回登录失败结果
        if(!empLogin.getPassword().equals(employee.getPassword())){
            throw new RuntimeException("密码不正确");
        }
        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(empLogin.getStatus() == 0){//代表员工已经警用
            throw new RuntimeException("该用户已禁用");
        }
        //

        return empLogin;
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    public boolean add(Employee employee) {


        //数据库增删改，三个方法得返回值只有一个 int  影响得行数
        int row = EmployeeMapper.insert(employee);

        if(row <= 0){
            return false;
        }
        return true;
    }

    @Override
    public List<Employee> findAll(int page, int pageSize) {

        //计算出查询得起始位置
        page = (page-1)*pageSize; //1   0  1  2
        List<Employee> employees = EmployeeMapper.seletAll(page,pageSize);
        return employees;
    }

    @Override
    public List<Employee> findByLikeName(int page, int pageSize, String name) {

        //计算出查询得起始位置
        page = (page-1)*pageSize; //1   0  1  2
        List<Employee> employees = EmployeeMapper.selectByLikeName(page,pageSize,"%"+name+"%");
        return employees;
    }

    @Override
    public Integer selectCount() {

        int count = EmployeeMapper.selectCount();
        return count;
    }
}
